package com.css.dzj.dzjportal.modules.jgaction.checkAction.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.dzj.dzjportal.common.util.R;
import com.css.dzj.dzjportal.common.util.excel.ExcelData;
import com.css.dzj.dzjportal.common.util.excel.ExportExcelUtils;
import com.css.dzj.dzjportal.common.util.http.HttpClientUtil;
import com.css.dzj.dzjportal.modules.jgaction.checkAction.vo.ApJgxwCheckAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/checkaction")
@PropertySource(value = "classpath:base.properties")
public class CheckActionController {
    @Value("${AP_URL}")
    String AP_URL;
    @Autowired
    private HttpServletRequest request;
    /**
     * @param year
     * @return
     */
    @GetMapping("/map")
    public R getTotalByYear(String year) {

        try {
            String[] mapPro = new String[]{"南海诸岛", "北京", "天津", "上海", "重庆", "河北", "河南", "云南", "辽宁", "黑龙江", "湖南", "安徽", "山东", "新疆", "江苏", "浙江", "江西", "湖北", "广西", "甘肃", "山西", "内蒙古", "陕西", "吉林", "福建", "贵州", "广东", "青海", "西藏", "四川", "宁夏", "海南", "台湾", "香港", "澳门"};
            /***
             * 获取检查行为
             */
            String msg = HttpClientUtil.doGet(AP_URL + "/check/countbyyear?year=" + year);
            JSONObject jsonObject = JSON.parseObject(msg);
            Object count = jsonObject.get("count");
            Map<String, Object> mapCheck = JSONObject.parseObject(count.toString());
            /**
             * 获取处罚行为
             */
            String msgPunish = HttpClientUtil.doGet(AP_URL + "/punish/punishyear?year=" + year);
            JSONObject jsonPunish = JSON.parseObject(msgPunish);
            Object punishOb = jsonPunish.get("count");
            Map<String, Object> mapPunish = JSONObject.parseObject(punishOb.toString());

            /**
             * 获取强制行为
             */
            String msgForce = HttpClientUtil.doGet(AP_URL + "/force/forceyear?year=" + year);
            JSONObject jsonForce = JSON.parseObject(msgForce);
            Object forceOb = jsonForce.get("count");
            Map<String, Object> mapForce = JSONObject.parseObject(forceOb.toString());

            /**
             * 获取其他行为
             */
            String msgOther = HttpClientUtil.doGet(AP_URL + "/other/otheryear?year=" + year);
            JSONObject jsonOther = JSON.parseObject(msgOther);
            Object otherOb = jsonOther.get("count");
            Map<String, Object> mapOther = JSONObject.parseObject(otherOb.toString());
            /**
             * 获取建设单位
             */
            String msgCon = HttpClientUtil.doGet(AP_URL + "/constr/countconstryear?year=" + year);
            JSONObject jsonCon = JSON.parseObject(msgCon);
            Object constr = jsonCon.get("count");
            Map<String, Object> mapCon = JSONObject.parseObject(constr.toString());
            /**
             * 获取安评单位
             */
            String msgUnit = HttpClientUtil.doGet(AP_URL + "/evalunit/countunityear?year=" + year);
            JSONObject jsonUnit = JSON.parseObject(msgUnit);
            Object unit = jsonUnit.get("count");
            Map<String, Object> mapUnit = JSONObject.parseObject(unit.toString());


            List<Map<String, Object>> list = new ArrayList();
            list.add(mapCheck);
            list.add(mapPunish);
            list.add(mapForce);
            list.add(mapOther);
            list.add(mapCon);
            list.add(mapUnit);
            Map<String, Object> mapAll = new HashMap<>();
            for (Map<String, Object> map : list) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String key = entry.getKey();
                    Integer value = (Integer) entry.getValue();
                    Integer valueAll = (Integer) mapAll.get(entry.getKey());
                    if (valueAll == null) {
                        mapAll.put(key, value);
                    } else {
                        valueAll = valueAll.intValue() + value.intValue();
                        mapAll.put(key, valueAll);
                    }
                }
            }
            List<Map<String, Object>> listNew = new ArrayList();
            Integer num = 0;
            for (Map.Entry<String, Object> entry : mapAll.entrySet()) {
                HashMap map = new HashMap();
                String name = entry.getKey();
                Integer value = (Integer) entry.getValue();
                num += value;
                map.put("name", name);
                map.put("value", value);
                listNew.add(map);
            }
            for(String arr:mapPro){
                HashMap mapNew=new HashMap();
                for (Map map:listNew) {
                    String str=(String)map.get("name");
                    if(!arr.equals(str)){
                        mapNew.put("name",arr);
                        mapNew.put("value",0);
                    }
                }
                listNew.add(mapNew);
            }
            String data = JSON.toJSONString(listNew);
            return R.ok().put("data", data).put("cityTotal", num);

        }catch (Exception e){
            return R.error(e.getMessage());
        }

    }

    /***
     * 分页查询检查行为
     * @param superviseItemImplementCode
     * @param checkActionName
     * @param checkActionCode
     * @param checkForm
     * @param checkType
     * @param checkMode
     * @param endDate
     * @param startDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getcheck")
    public R getCheckAction(@RequestParam(required = false) String superviseItemImplementCode,
                            @RequestParam(required = false) String checkActionName,
                            @RequestParam(required = false) String checkActionCode,
                            @RequestParam(required = false) String checkForm,
                            @RequestParam(required = false) String checkType,
                            @RequestParam(required = false) String checkMode,
                            @RequestParam(required = false) String endDate,
                            @RequestParam(required = false) String startDate,
                            @RequestParam(required = false) Integer pageNo,
                            @RequestParam(required = false) Integer pageSize) {
        HashMap<String, String> map = new HashMap<>();
        map.put("superviseItemImplementCode", superviseItemImplementCode);
        map.put("checkActionName", checkActionName);
        map.put("checkActionCode", checkActionCode);
        map.put("checkForm", checkForm);
        map.put("checkType", checkType);
        map.put("checkMode", checkMode);
        map.put("endDate", endDate);
        map.put("startDate", startDate);
        map.put("pageNo", pageNo.toString());
        map.put("pageSize", pageSize.toString());
        String msg = HttpClientUtil.doGet(AP_URL + "/check/getAll", map);
        JSONObject object = JSON.parseObject(msg);
        return R.ok().put("data", object);
    }

    /**
     * 查看检查行为详情
     *
     * @param actionId
     * @return
     */
    @GetMapping("/getById")
    public R getById(String actionId) {
        String msg = HttpClientUtil.doGet(AP_URL + "/check/getCheck?" + actionId);
        JSONObject object = JSON.parseObject(msg);
        return R.ok().put("data", object);
    }

    /***
     * 获取检查行为总数
     * @return
     */
    @GetMapping("/getcount")
    public R getCount() {
        String msg = HttpClientUtil.doGet(AP_URL + "/check/num");
        JSONObject object = JSON.parseObject(msg);
        return R.ok().put("data", object);
    }

    /**
     * 导出全部
     * @param superviseItemImplementCode
     * @param checkActionName
     * @param checkActionCode
     * @param checkForm
     * @param checkType
     * @param checkMode
     * @param response
     * @return
     * @throws ParseException
     */
    @GetMapping("/exportAll")
    public R exportAll(@RequestParam(required = false) String superviseItemImplementCode,
                    @RequestParam(required = false) String checkActionName,
                    @RequestParam(required = false) String checkActionCode,
                    @RequestParam(required = false) String checkForm,
                    @RequestParam(required = false) String checkType,
                    @RequestParam(required = false) String checkMode,
                    @RequestParam(required = false) String checkDate,
                    HttpServletResponse response) throws ParseException {
        HashMap<String, String> map = new HashMap<>();
        map.put("superviseItemImplementCode", superviseItemImplementCode);
        map.put("checkActionName", checkActionName);
        map.put("checkActionCode", checkActionCode);
        map.put("checkForm", checkForm);
        map.put("checkType", checkType);
        map.put("checkMode", checkMode);
        map.put("checkDate", checkDate);
        String msg = HttpClientUtil.doGet(AP_URL + "/check/getList", map);
        JSONArray array = JSON.parseArray(msg);
        List<ApJgxwCheckAction> list = new ArrayList<>();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        for (Object ob : array) {
            Map<String, Object> map1 = JSONObject.parseObject(ob.toString());
            ApJgxwCheckAction apJgxwCheckAction = new ApJgxwCheckAction();
            apJgxwCheckAction.setRecordUniqueIdentity(map1.get("recordUniqueIdentity").toString());
            apJgxwCheckAction.setSuperviseItemImplementCode(map1.get("superviseItemImplementCode").toString());
            apJgxwCheckAction.setSuperviseItemCheckIcode(map1.get("superviseItemCheckIcode").toString());
            apJgxwCheckAction.setImplementInstitution(map1.get("implementInstitution").toString());
            apJgxwCheckAction.setCheckActionName(map1.get("checkActionName").toString());
            apJgxwCheckAction.setCheckActionCode(map1.get("checkActionCode").toString());
            apJgxwCheckAction.setCheckForm(map1.get("checkForm").toString());
            apJgxwCheckAction.setCheckType(map1.get("checkType").toString());
            apJgxwCheckAction.setCheckMode(map1.get("checkMode").toString());
            apJgxwCheckAction.setCheckResult(map1.get("checkResult").toString());
            String checkDate1 = sf.format(map1.get("checkDate"));
            apJgxwCheckAction.setCheckDate(sf.parse(checkDate1));
            list.add(apJgxwCheckAction);
        }
        export(response,list);
        return R.ok();
    }

    /**
     * 通过ids导出选中数据
     * @param response
     * @param ids
     * @return
     * @throws ParseException
     */
    @GetMapping("/exportByIds")
    public R exportByIds(HttpServletResponse response,String ids) throws ParseException {
        String msg = HttpClientUtil.doGet(AP_URL + "/check/getList/"+ids);
        JSONArray array = JSON.parseArray(msg);
        List<ApJgxwCheckAction> list = new ArrayList<>();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        for (Object ob : array) {
            Map<String, Object> map1 = JSONObject.parseObject(ob.toString());
            ApJgxwCheckAction apJgxwCheckAction = new ApJgxwCheckAction();
            apJgxwCheckAction.setRecordUniqueIdentity(map1.get("recordUniqueIdentity").toString());
            apJgxwCheckAction.setSuperviseItemImplementCode(map1.get("superviseItemImplementCode").toString());
            apJgxwCheckAction.setSuperviseItemCheckIcode(map1.get("superviseItemCheckIcode").toString());
            apJgxwCheckAction.setImplementInstitution(map1.get("implementInstitution").toString());
            apJgxwCheckAction.setCheckActionName(map1.get("checkActionName").toString());
            apJgxwCheckAction.setCheckActionCode(map1.get("checkActionCode").toString());
            apJgxwCheckAction.setCheckForm(map1.get("checkForm").toString());
            apJgxwCheckAction.setCheckType(map1.get("checkType").toString());
            apJgxwCheckAction.setCheckMode(map1.get("checkMode").toString());
            apJgxwCheckAction.setCheckResult(map1.get("checkResult").toString());
            String checkDate = sf.format(map1.get("checkDate"));
            apJgxwCheckAction.setCheckDate(sf.parse(checkDate));
            list.add(apJgxwCheckAction);
        }
        export(response,list);
        return R.ok();
    }

    /***
     * 导出逻辑
     * @param response
     * @param list
     */
    private void export(HttpServletResponse response, List<ApJgxwCheckAction> list) {
        if (list == null || list.size() < 0) {
            throw new RuntimeException("节假日为空");
        }
        // 创建导出实体
        ExcelData data = new ExcelData();
        data.setName("行政检查行为监管表");
        /**
         * 设置Excel标题
         */
        ArrayList<String> titles = new ArrayList<>();
        titles.add("记录唯一标识");
        titles.add("监管事项目录编码");
        titles.add("监管事项检查实施清单编码");
        titles.add("检查行为名称");
        titles.add("检查行为编号");
        titles.add("实施机构");
        titles.add("检查类别");
        titles.add("检查方式");
        titles.add("检查结果");
        titles.add("检查时间");
        data.setTitles(titles);
        /**
         * 处理行数据
         */
        ArrayList<List<Object>> rows = new ArrayList<>();
        for (ApJgxwCheckAction apJgxwCheckAction : list) {
            ArrayList<Object> row = new ArrayList<>();
            row.add(apJgxwCheckAction.getRecordUniqueIdentity());
            row.add(apJgxwCheckAction.getSuperviseItemImplementCode());
            row.add(apJgxwCheckAction.getSuperviseItemCheckIcode());
            row.add(apJgxwCheckAction.getCheckActionName());
            row.add(apJgxwCheckAction.getCheckActionCode());
            row.add(apJgxwCheckAction.getImplementInstitution());
            if (apJgxwCheckAction.getCheckType().equals("1")) {
                row.add("现场检查");
            }
            if (apJgxwCheckAction.getCheckType().equals("2")) {
                row.add("非现场检查");
            }
            if (apJgxwCheckAction.getCheckMode().equals("1")) {
                row.add("“双随机、一公开”监管");
            }
            if (apJgxwCheckAction.getCheckMode().equals("2")) {
                row.add("重点监管");
            }
            if (apJgxwCheckAction.getCheckMode().equals("3")) {
                row.add("信用监管");
            }
            if (apJgxwCheckAction.getCheckResult().equals("1")) {
                row.add("未发现问题终止检查并向监管对象告知检查结果");
            }
            if (apJgxwCheckAction.getCheckResult().equals("2")) {
                row.add("发现问题作出责令改正等行政命令");
            }
            if (apJgxwCheckAction.getCheckResult().equals("3")) {
                row.add("发现问题做出行政指导");
            }
            if (apJgxwCheckAction.getCheckResult().equals("4")) {
                row.add("发现问题作出行政处罚决定");
            }
            if (apJgxwCheckAction.getCheckResult().equals("5")) {
                row.add("发现问题作出行政强制决定");
            }
            if (apJgxwCheckAction.getCheckResult().equals("6")) {
                row.add("发现问题作出其他具体行政行为");
            }
            row.add(apJgxwCheckAction.getCheckDate());
            rows.add(row);
        }
        data.setRows(rows);
        try {
            // 导出
            ExportExcelUtils.exportExcel(request,response, "行政检查行为监管表.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
